package com.xq.jltx.frescosimple.activity;


import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xq.jltx.frescosimple.R;
import com.xq.jltx.frescosimple.config.Constants;
import com.xq.jltx.frescosimple.display.DefaultDrawables;
import com.xq.jltx.frescosimple.fragment.BackHandledFragment;
import com.xq.jltx.frescosimple.fragment.BackHandledInterface;
import com.xq.jltx.frescosimple.fragment.HomeFragment;
import com.xq.jltx.frescosimple.utils.FileUtils;
import com.xq.jltx.frescosimple.utils.FrescoUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class HomeActivity extends AppCompatActivity implements BackHandledInterface{
    private TextView statsDisplay;
    private Spinner loaderSelect;
    private FrameLayout container;

    //当前显示的Fragment页面
    private BackHandledFragment mBackHandedFragment;
    private int mCurrentAdapterIndex = 1;
    private void assignViews() {
        statsDisplay = (TextView) findViewById(R.id.stats_display);
        loaderSelect = (Spinner) findViewById(R.id.loader_select);
        container = (FrameLayout) findViewById(R.id.container);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        DefaultDrawables.init(getResources());
        assignViews();
        loaderSelect.setSelection(mCurrentAdapterIndex);
        loaderSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                if(mBackHandedFragment != null){
                    Bundle bundleArg = mBackHandedFragment.getArguments();
                    if(bundleArg == null){
                        bundleArg = new Bundle();
                    }
                    bundleArg.putInt(Constants.LOADER_INDEX,position);
                    mBackHandedFragment.onUpdateFragment(bundleArg);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Constants.IMAGES[0] = FrescoUtils.getUriPathFromPath(getApplicationContext(),FrescoUtils.LOCAL_ASSET_SCHEME_INT,"huoying.jpg");
        if(savedInstanceState == null){
            HomeFragment homeFragment =  HomeFragment.newInstance("ImgCacheDemo", Constants.IMAGES,mCurrentAdapterIndex);
            fragmentTransaction.add(R.id.container,homeFragment,HomeFragment.class.getSimpleName());
            fragmentTransaction.commit();
        }
        if(!FileUtils.isExistFile(FileUtils.getSDPath() + "huoying2.jpg")){
            AssetManager assetManager = getAssets();
            try {
                InputStream inputStream = assetManager.open("huoying2.jpg");
                FileOutputStream fos = new FileOutputStream(FileUtils.getSDPath() + "huoying2.jpg");
                byte[] buffer = new byte[inputStream.available()];
                int size = 0;
                while((size = inputStream.read(buffer, 0, buffer.length)) != -1)
                {
                    fos.write(buffer, 0, size);
                }
                inputStream.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(!FileUtils.isExitInData(getApplicationContext(),"huoying3.jpg")){
            AssetManager assetManager = getAssets();
            try {
                InputStream inputStream = assetManager.open("huoying3.jpg");
                File fileDic = getApplicationContext().getFilesDir();
                FileOutputStream fos = new FileOutputStream(fileDic.getAbsolutePath() + "/huoying3.jpg");
                byte[] buffer = new byte[1024 * 2];
                int size = 0;
                while((size = inputStream.read(buffer, 0, buffer.length)) != -1)
                {
                    fos.write(buffer, 0, size);
                }
                inputStream.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
/*        int num = fragmentManager.getBackStackEntryCount();
        String numString = "++++++++++++++++++++++++++++++++++Fragment回退栈数量："+num;
        for (int i = 0; i < num; i++) {
            FragmentManager.BackStackEntry backstatck = fragmentManager.getBackStackEntryAt(i);
        }*/
    }

    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        mBackHandedFragment = selectedFragment;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.item_clear_memory_cache:
                Toast.makeText(this,"清理缓存",Toast.LENGTH_SHORT).show();
                return true;
            case R.id.show_track:
                Toast.makeText(this,"显示仪表",Toast.LENGTH_SHORT).show();
                return true;
            default:
                return false;
        }

    }

    @Override
    public void onBackPressed() {
        if(mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()){
            if(getSupportFragmentManager().getBackStackEntryCount() == 0){
                super.onBackPressed();
            }else{
                getSupportFragmentManager().popBackStack();
            }
        }
    }

    @Override
    public void onBackResultFromFragment(int requestCode, Bundle bundle) {

    }
}
